﻿using System.Linq;
using System.Web.Mvc;
using ShoppingCart.Domain.Entities;
using ShoppingCart.Domain.Models;
using ShoppingCart.Business.Concrete;
using ShoppingCart.Business.Abstract;
using Ninject;

namespace ShoppingCart.WebUI.Controllers {

    public class CartController : Controller {
        
        [Inject]
        public IProductService productService { get; set; }

        public ViewResult Summary(Cart cart) {
            return View(cart);
        }

        public RedirectToRouteResult AddToCart(Cart cart, int productId, string returnUrl) {
            Product product = productService.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null) {
                cart.AddItem(product, 1);
            }
            return RedirectToAction("Index", new { returnUrl });
        }

        public RedirectToRouteResult RemoveFromCart(Cart cart, 
            int productId, string returnUrl) {

                Product product = productService.Products
                .FirstOrDefault(p => p.ProductID == productId);

            if (product != null) {
                cart.RemoveLine(product);
            }
            return RedirectToAction("Index", new { returnUrl });
        }

        public ViewResult Index(Cart cart, string returnUrl) {
            return View(new CartIndexViewModel {
                Cart = cart,
                ReturnUrl = returnUrl
            });
        }
    }
}
